package br.ufes.inf.lprm.cwtools.web.controller;

import java.util.Date;
import java.util.List;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.ValidationMessage;
import br.ufes.inf.lprm.cwtools.entities.TrackingInfo;
import br.ufes.inf.lprm.cwtools.entities.dao.TrackingInfoDAO;
import br.ufes.inf.lprm.cwtools.entities.util.TrackRequest;

@Resource
@Path("/tracker")
public class TrackingInfoController {
	private TrackingInfoDAO dao;
	private Result result;
	private Validator validator;

	public TrackingInfoController(final TrackingInfoDAO dao, final Validator validator, final Result result){
		this.dao = dao;
		this.result = result;
		this.validator = validator;
	}
	
	@Get
	@Path("/{lat}/{lng}/{range}")
	public List<TrackingInfo> list(double lat, double lng, double range){
		TrackRequest track = new TrackRequest();
		track.setLatitude(lat);
		track.setLongitude(lng);
		track.setRange(range);
		
		result.include("trackRequest", track);
		return dao.listAllInRange(track.getLatitude(), track.getLongitude(), track.getRange());
	}
	
	@Post
	@Path("/update")
	public void update(TrackingInfo trackingInfo){
		//Validação das coordenadas
		if(Math.abs(trackingInfo.getLatitude()) > 90){
			validator.add(new ValidationMessage("Latitude inválida.", "Dados inválidos"));
		}
		if(Math.abs(trackingInfo.getLongitude()) > 180){
			validator.add(new ValidationMessage("Longitude inválida.", "Dados inválidos"));
		}
		//Validação da acuidade
		if(trackingInfo.getAccuracy() > 1000){
			validator.add(new ValidationMessage("Acuidade inválida.", "Dados inválidos"));
		}
		
		validator.onErrorUsePageOf(this).update(null);
		
		dao.insert(trackingInfo);
	}
	
	@Get
	@Path("/random_populate")
	public void random(){
		TrackingInfo ti = new TrackingInfo();
		ti.setAccuracy(20*Math.random());
		ti.setDateUpdate(new Date());
		ti.setUserId((int)(99*Math.random()));
		ti.setLatitude(90*(2*Math.random()-1));
		ti.setLongitude(180*(2*Math.random()-1));
		dao.insert(ti);
		result.redirectTo("/tracker/1/1/1");
	}
}
